<?php
namespace Admin\Behaviors;

class UserBehavior extends \Think\Behavior{
	//行为执行入口
	public function run(&$param){
		$uid = session("userid");
		//未登录，则跳转到登陆页面
		if( empty($uid) ){
			if( IS_AJAX ){
				echo "<script>window.location.href='".U('login/dologin')."';</script>";
			}else{
				redirect(U('login/dologin'));
			}
			die;
		}

		//锁屏检测
		$is_lock_screen = session('_lock_screen');
		$str = strtolower( CONTROLLER_NAME.ACTION_NAME );
		if( $is_lock_screen && $str!="indexlock" ){
			redirect(U('Index/lock'));
			die;
		}

        //首次登陆，修改密码
		//if(session('user_first_login') && $str!= "indexindex"&& $str!= "userprofile")
        //{
        //    redirect(U('User/profile'));
        //    die;
        //}

		//权限检测
		$adminer = C('ADMINISTRATOR_USERID');
		$action = ACTION_NAME;
		#$ispublic = preg_match('/^public_/',$action);
		$nowmca = strtolower(MODULE_NAME.'_'.CONTROLLER_NAME.'_'.$action);

        $c = MODULE_NAME."\Controller\\".CONTROLLER_NAME."Controller";
        $a = ACTION_NAME;
		if( method_exists($c,$a) )
        {
    		$method = new \ReflectionMethod($c, $a);
    		$method_doc = $method->getDocComment();
    		if( !empty($method_doc) ){
    			preg_match("/\@privilege(.+)/", $method_doc,$mat);
    			$ispublic = preg_match('/^public/',trim($mat[1]));
    		}

        	if(!in_array(session('userid'),$adminer) && !$ispublic && !in_array($nowmca, session('priv_menu')) && $nowmca!='admin_index_index'){
        		if( IS_AJAX && I('post.') ){
        			$return_arr = array(
        					'status'=>403,
        					'msg'=>L('no_priv')
        			);
        			echo json_encode($return_arr);exit;
        		}else if( I('get._from')=='html' ){
                    //如果是中心模板页面，直接跳转到没有权限页面
                    redirect(U('Index/noprivilege'));
                    exit();
        		}else{
                    echo "<script>window.history.go(-1);showhidetip('".L('no_priv')."',2);</script>";exit;
                }
        	}
        }
	}
}
